package broker;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;

import common.Settings;


public class CLIBroker {

	public static void main(String[] args) throws Exception {
		CLIBroker cliBroker = new CLIBroker();
		cliBroker.run(args);
	}

	private BrokerImpl broker;

	public CLIBroker() throws Exception {
		broker = new BrokerImpl();
	}

	private void printErrorMessage() {
		System.out.println("Incorrect command, try to use:");
		System.out.println(" exit");
		System.out.println(" entropy <requeue_ratio_percentage>");
		System.out.println(" sleep   <sleep_time_millis>");
	}

	private void run(String[] args) throws Exception {
		if (args.length != 2) {
			System.out
					.println("Usage: clibroker <network_interface_name> <broker_manager_ip>");
			System.out
					.println(" <network_interface_name> the name of the network interface to use (run ifconfig to view possible choices)");
			System.out
					.println(" <broker_manager_ip>      the ip of of the machine where the broker manager is running");
		}

		// Run the broker
		broker.start(args[0], new URI(args[1]));

		// Grab input stream
		InputStreamReader inStream = new InputStreamReader(System.in);
		BufferedReader in = new BufferedReader(inStream);
		String cmd = "";
		String[] cmdParts;

		// Cyclically read and execute commands
		while (true) {
			cmd = in.readLine();
			cmdParts = cmd.split(" ");

			// Null commands
			if (cmdParts == null || cmdParts.length == 0 || cmdParts[0] == null) {
				printErrorMessage();
				continue;
			}

			// Exit
			else if (cmdParts[0].equals("exit")) {
				if (cmdParts.length != 1) {
					printErrorMessage();
					continue;
				}
				try {

					// Uncomment these lines to enable fast broker stop
					// Settings.queueEntropy = 0f;
					// Settings.sleepTime = 0;
					broker.stop();
					return;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			// Change requeue ratio
			else if (cmdParts[0].equals("entropy")) {
				if (cmdParts.length != 2) {
					printErrorMessage();
					continue;
				}
				synchronized (Settings.queueEntropy) {
					try {
						Settings.queueEntropy = Float.parseFloat(cmdParts[1]) / 100;
					} catch (Exception e) {
						printErrorMessage();
						continue;
					}
					continue;
				}
			}

			// Change dispatchers sleep time
			else if (cmdParts[0].equals("sleep")) {
				if (cmdParts.length != 2) {
					printErrorMessage();
					continue;
				}
				synchronized (Settings.sleepTime) {
					try {
						Settings.sleepTime = Integer.parseInt(cmdParts[1]);
					} catch (Exception e) {
						printErrorMessage();
						continue;
					}
					continue;
				}
			}

			else {
				printErrorMessage();
			}
		}
	}
}
